package com.nineclock.attendance.config;


import com.nineclock.attendance.mapper.AttendGroupMapper;
import com.nineclock.attendance.pojo.AttendGroup;
import com.nineclock.attendance.service.AttendPunchService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysOrganizationFeign;
import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
import com.xxl.job.core.handler.annotation.XxlJob;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SendAttendMailTask {

    @Autowired
    private AttendGroupMapper attendGroupMapper;

    @Autowired
    private AttendPunchService attendPunchService;

    @Autowired
    private SysOrganizationFeign organizationFeign;

    public SendAttendMailTask ( ) {
    }

    @XxlJob ("countAttendanceAndSendMail")
    public void countAttendanceAndSendMail() throws MessagingException, IOException, javax.mail.MessagingException {
        log.info("---------> 开始启动任务 , 统计企业本月考勤数据, 并生成报表, 发送邮件给企业管理员");

        //1. 获取所有的企业ID集合
        log.info("---------> 获取企业ID集合");
        Set<Long> companyIds = this.queryAllCompanyIds();

        for (Long companyId : companyIds) {
            log.info("---------> 统计每个企业的考勤记录情况, 并生成Excel报表");
            //2. 构造Excel文件 ---> 统计每个的企业的本月考勤情况 ;
            String excelFile = attendPunchService.generateExcelReportByCompanyId(companyId);
            if(excelFile == null){
                continue;
            }

            log.info("---------> 获取企业管理员邮箱");
            //3. 获取每一个企业主管理员邮箱
            SysCompanyUserDTO userDTO = organizationFeign.queryAdminByCompanyId(companyId).getData();
            if(userDTO == null){
                log.error("未获取到企业 %s 的管理员信息, 无法发送邮件",companyId.toString());
            }

            log.info("---------> 数据准备完毕, 发送报表统计邮件");
            //4. 调用JavaMail发送邮件
            this.sendMail(userDTO, excelFile);
            log.info("---------> 邮件发送完毕");
        }

        log.info("---------> 此次任务执行完毕, 已经发送邮件给企业管理员");
    }



    @Autowired
    private JavaMailSender javaMailSender;

    @Value ("${spring.mail.username}")
    private String from;

    /**
     * 发送附件邮件给企业的主管理员
     * @param userDTO  企业主管理员信息
     * @param excelFile 附件文件名
     */
    private void sendMail(SysCompanyUserDTO userDTO, String excelFile) throws MessagingException, javax.mail.MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

        messageHelper.setFrom(from);
        messageHelper.setTo(userDTO.getEmail());
        messageHelper.setSubject("考勤数据报表");
        messageHelper.setText("您好, 本月考勤数据报表已经生成, 请查收附件, 谢谢");

        messageHelper.addAttachment("本月考勤数据.xlsx",new File (excelFile));

        javaMailSender.send(mimeMessage);

    }


    /**
     * 获取所有的企业ID集合
     * @return
     */
    private Set<Long> queryAllCompanyIds() {
        List<AttendGroup> attendGroups = attendGroupMapper.selectList(null);
        Set<Long> ids = attendGroups.stream().map(attendGroup -> {
            return attendGroup.getCompanyId();
        }).collect( Collectors.toSet());

        return ids;
    }

}